﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;  //引用命名空间

namespace MyTest
{
    /// <summary>
    /// 教员:薛海
    /// 微信:xuehai03
    /// QQ:289477003
    /// Access数据库示例
    /// 2019-2-20
    /// </summary>
    public partial class frmAccess : Form
    {
        public frmAccess()
        {
           
            InitializeComponent();
        }

        const string connStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=DB\MySchool.accdb";
        OleDbConnection conn = new OleDbConnection(connStr);


        DataSet ds;
        OleDbDataAdapter adapter;

        //窗体加载事件
        private void frmAccess_Load(object sender, EventArgs e)
        {
            
            //getInfo();
        }

        public void getInfo()
        {
            try
            {
                ds = new DataSet();
                string sqlStr = "select * from student";
                adapter = new OleDbDataAdapter(sqlStr, conn);

                if (ds.Tables["student"] != null)
                {
                    ds.Tables["student"].Clear();
                }

                adapter.Fill(ds, "student");
                this.dataGridView1.DataSource = ds.Tables["student"];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //登录事件
        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                conn.Open();
                string sqlStr = string.Format("select count(*) from student where studentNo ='{0}' and loginPwd='{1}'", this.txtUserName.Text, this.txtPwd.Text);
                OleDbCommand comm = new OleDbCommand(sqlStr, conn);
                int result = (int)comm.ExecuteScalar();
                if (result > 0)
                {
                    this.dataGridView1.AutoGenerateColumns = false;
                    MessageBox.Show("登录成功");
                    getInfo();
                }
                else
                {
                    MessageBox.Show("登录失败");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                conn.Close();
            }
            
        }
    }
}
